package io.yx.flx.test;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.setting.Setting;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import javax.imageio.ImageIO;
import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static io.yx.flx.Main.getBasePath;
import static io.yx.flx.service.UploadServiceImpl.getContentType;

/**
 * @author YX
 * @date 2022/8/16 10:52
 * 给出现有的url,将其重新压缩后上传到对应的文件夹
 */
public class Recompress {
    public static final Setting setting;
    private static final String envFileName = "env.setting";

    static {
        byte[] bytes = ResourceUtil.readBytes(envFileName);
        String targetEnvFilePath = getBasePath() + File.separator + envFileName;
        if (!FileUtil.exist(targetEnvFilePath)) {
            File file = FileUtil.file(targetEnvFilePath);
            FileUtil.writeBytes(bytes, file);
        }
        String envFilePath = getBasePath() + File.separator + envFileName;
        setting = new Setting(envFilePath);
        Boolean openSSL = setting.getBool("openOSS");
        if (Boolean.TRUE.equals(openSSL)) {
            Setting ossSetting = new Setting(setting.getStr("ossConfigPath"));
            Set<Map.Entry<String, String>> entries = ossSetting.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                System.setProperty(entry.getKey(), entry.getValue());
            }
        }
    }

    private static final String endpoint = System.getProperty("oss.endpoint");
    private static final String accessKeyId = System.getProperty("oss.accessKeyId");
    private static final String accessKeySecret = System.getProperty("oss.accessKeySecret");
    private static final String bucketName = System.getProperty("oss.bucketName");
    private static final String folder = System.getProperty("oss.folder");
    private static final String folderCompress = System.getProperty("oss.folderCompress");


    public static void main(String[] args) {
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        Recompress recompress = new Recompress();
        List<String> strings = FileUtil.readUtf8Lines("C:/Users/YX/Desktop/img.txt");
        for (String url : strings) {
            url = StrUtil.trim(url);
            File file = recompress.getFile(url);
            recompress.comporessFile(file);
            String resultUrl = recompress.reupload(file, url, oss);
            System.out.println(resultUrl);
        }
    }

    public File getFile(String url) {
        File dist = new File("D:/tmp");
        return HttpUtil.downloadFileFromUrl(url, dist, 300000);
    }

    public void comporessFile(File file) {
        FileUtil.copy(file, new File(file.getAbsolutePath() + ".bak"), true);
        try {
            int width = ImageIO.read(file).getWidth();
            if (width > 1000) {
                int newWidth = 1000;
                Mat mat = Imgcodecs.imread(file.getAbsolutePath());
                // 计算等比缩放的高度
                float scale = (float) mat.width() / newWidth;
                int newHeight = (int) (mat.height() / scale);
                Mat newMat = new Mat();
                Imgproc.resize(mat, newMat, new Size(newWidth, newHeight));
                Imgcodecs.imwrite(file.getAbsolutePath(), newMat);
            }
        } catch (Exception e) {
            e.getMessage();
        }
    }

    public String reupload(File file, String url, OSS oss) {
        //创建每月的文件夹
        String final_folder = "GPAI5/2022-08/";
        String targetFileName = FileUtil.getName(url);

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.length());
        metadata.setContentType(getContentType(file.getName()));
        metadata.setContentEncoding("utf-8");
        metadata.setContentDisposition("filename/filesize=" + targetFileName + "/" + file.length() + "Byte.");

        oss.putObject(bucketName, final_folder + targetFileName, file, metadata);

        return getUrl(oss, final_folder, targetFileName);
    }

    public String getUrl(OSS oss, String folder, String fileName) {
        // 设置URL过期时间为10年 3600l* 1000*24*365*10

        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);

        //避免出现重复拼接图片地址
        String path = folder.endsWith("/") ? folder + fileName : folder + "/" + fileName;

        // 生成URL
        URL url = oss.generatePresignedUrl(bucketName, path, expiration);
        if (url != null) {

//            String result = url.toString().replace("test50.oss-cn-shanghai.aliyuncs.com", "cdnimg.gpai.net");
            String result = url.toString().replaceAll("test50.+\\.aliyuncs\\.com", "cdnimg.gpai.net");

            result = result.substring(0, result.indexOf("?Expires"));

            return result;
        } else {
            return null;
        }
    }

}
